package com.shi.vueblog.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shi.vueblog.common.result.Result;
import com.shi.vueblog.entity.Blog;
import com.shi.vueblog.service.BlogService;
import com.shi.vueblog.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2020-06-07
 */
@Slf4j
@RestController
public class BlogController {

    @Autowired
    BlogService blogService;

    //获取博客列表
    @GetMapping("/blogs")
    public Result blogs(@RequestParam(defaultValue = "1") Integer currentPage) {
        Page page = new Page(currentPage,5);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created").eq("status","0"));
        return Result.succ(pageData);
    }


    //获取博客列表

    @RequiresAuthentication
    @GetMapping("/blog/myBlogs")
    public Result myBlogs(@RequestParam(defaultValue = "1") Integer currentPage,
                          @RequestParam Long uid) {
        Page page = new Page(currentPage,5);
//        uId=2L;
        System.out.println(uid);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created").eq("status","0").eq("user_id",uid));
        return Result.succ(pageData);
    }


    //根据id获取文章详情 @PathVariable是spring3.0的一个新功能：接收请求路径中占位符的值
    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id){
        Blog blog = blogService.getById(id);
        //断言 blog不是空，如果是空就报错（文章不存在）
        Assert.notNull(blog,"文章不存在");
        return Result.succ(blog);
    }

    //@RequiresAuthentication 需要登录才能调用注解
    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog){
        Blog temp = null;

        if (blog.getId() != null){
            temp=blogService.getById(blog.getId());
            //仅userID相同的才能编辑
            Assert.isTrue(temp.getUserId().longValue() == ShiroUtil.getProfile().getId().longValue(), "没有权限编辑");

        }else  {
            temp = new Blog();
            temp.setUserId(ShiroUtil.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }
        //BeanUtil 是hutool
        BeanUtil.copyProperties(blog,temp,"id","userId","created","status");
        blogService.saveOrUpdate(temp);// saveOrUpdae 如果id存在就更新 如果不存在就新建
        return Result.succ("操作成功","null");
    }
}
